package com.lichuang.fruitvarietysm.cart.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.lichuang.fruitvarietysm.cart.entity.Shoppingcart;
import com.lichuang.fruitvarietysm.cart.feign.GoodSkuMapper;
import com.lichuang.fruitvarietysm.cart.feign.GoodsMapper;
import com.lichuang.fruitvarietysm.cart.feign.UserMapper;
import com.lichuang.fruitvarietysm.cart.feignEntity.Goods;
import com.lichuang.fruitvarietysm.cart.feignEntity.GoodsSkuAttr;
import com.lichuang.fruitvarietysm.cart.feignEntity.Goodssku;
import com.lichuang.fruitvarietysm.cart.feignEntity.User;
import com.lichuang.fruitvarietysm.cart.mapper.ShoppingcartMapper;
import com.lichuang.fruitvarietysm.cart.service.impl.ShoppingcartServiceImpl;
import com.lichuang.fruitvarietysm.cart.vo.ShoppingCartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author kangkang
 * @since 2019-06-10
 */
@RestController
@RequestMapping("//shoppingcart")
public class ShoppingcartController {

    @Autowired
    ShoppingcartServiceImpl shoppingcartService;

    @Autowired
    ShoppingcartMapper shoppingcartMapper;

    @Autowired
    GoodSkuMapper skuMapper;

    @Autowired
    private UserMapper userMapper;

    //添加购物车
    //@CookieValue("loginToken")String loginToken,
    @RequestMapping("/addCart")
    public int addCart(@RequestParam("userId") Integer userId,
                       @RequestParam("goodsId") Integer goodsId,
                          @RequestParam("skuValue")String skuValue
                      ){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String createTime=df.format(new Date());// new Date()为获取当前系统时间
        System.out.println(df.format(new Date()));

//先判断用户是否登录，没有登录就进行让用户去登录，登录过后在进行添加购物车。
//       User user= userMapper.getCurrentUser(loginToken);
//       if(user==null){
//           System.out.println("该用户没有登录");
//           return -1;
//       }
        //判断购物车是否存在在该商品
        int count=shoppingcartService.sCartYesOrNoGoods(userId,goodsId);
        //返回的状态信息
        int state;
        //不存在该商品就进行添加
        if(count == 0){
            //再先判断改该商品是否存在sku，不存在sku的可以直接添加购物车
            int skuCount=skuMapper.getSkuCount(goodsId);
            int  num=0;
            if(skuCount==0){
                    Goods goods=skuMapper.getGoods(goodsId);
                //进行购物车的添加
                  num = shoppingcartService.addCart(userId,goodsId,createTime, goods.getGoodsPrice(),-1);
            }else{
                /**
                 *存 在的话，前端需要先判断用户是否选择了规格，无选择返回让用户选择规格，
                 * 选则了规格就查该规格是对应哪个sku的值，该sku的id
                 * 然后进行添加购物车，
                 */
               Goodssku goodssku= skuMapper.getSku(goodsId,skuValue);
                num = shoppingcartService.addCart(userId, goodsId, createTime,goodssku.getGoodsPrice(),goodssku.getSkuId());
            }

            if(num==1){
                state=num;
                System.out.println("添加购物车成功");
            }else {
                state=num;
                System.out.println("添加购物车失败");
            }
        }else if(count==1) {
            //查找购物车某用户的某商品的所有信息
            Shoppingcart goodsCount=shoppingcartService.sCartGoodsNumber(userId,goodsId);
            //进行该购物车某用户的某商品的数量
            int goodsNum=goodsCount.getQuantity()+1;
            //进行修改购物车的某个数据的商品购买数量
            int upNum=   shoppingcartService.updateCatNum(goodsCount.getCartID(),goodsNum);
            if(upNum==1){
                state=upNum;
                System.out.println("添加更新购物车成功");
            }else {
                state=upNum;
                System.out.println("添加更新购物车失败");
            }
        }else {
            System.out.println("添加购物车有重复记录，用户："+userId+",商品:"+goodsId);
            state=-1;
        }
       return  state;
    }

//@CookieValue("loginToken")String loginToken
    @RequestMapping("/getShoppingCart")
    public Object getShoppingCartByUserId(Integer userId, int state){
//        User user = userMapper.getCurrentUser(loginToken);
//        if(user==null){
//            return "没有登陆";
//        }
        //判断用户是否已经登录，没有登录进行登录。

        //state：1代表全部商品，2代表是库存紧张商品
        List<Shoppingcart> shoppingCartList=new ArrayList<>();
        if(state==1){
            Shoppingcart shoppingcart=new Shoppingcart();
            shoppingcart.setUserId(userId);
            QueryWrapper queryWrapper=new QueryWrapper(shoppingcart);
            shoppingCartList=shoppingcartMapper.selectList(queryWrapper);
        }else  if(state==2){
            //查库存紧张的商品
            shoppingCartList= shoppingcartMapper.getList(userId);
        }

        List<ShoppingCartVo> cartVoList=new ArrayList<>();
        for (Shoppingcart cart : shoppingCartList) {
            ShoppingCartVo shoppingCartVo=new ShoppingCartVo();
              Goods goods=skuMapper.getGoods(cart.getGoodsId());
            //再先判断改该商品是否存在sku，
            int skuCount=skuMapper.getSkuCount(goods.getGoodsId());
            Goodssku goodssku;
            if(skuCount!=0){
               goodssku=  skuMapper.getSkuBySkuId(cart.getSkuId());
               //库存
                shoppingCartVo.setStockNumber(goodssku.getNumber());
                //重量
                shoppingCartVo.setGoodsWeight(goodssku.getGoodsWeight());
                //状态
                shoppingCartVo.setState(goodssku.getState());

                List<List> lists=skuMapper.getSkuText(cart.getSkuId());
                shoppingCartVo.setSku(lists);
            }else{
                //库存
                shoppingCartVo.setStockNumber(goods.getGoodsStock());
                shoppingCartVo.setGoodsWeight(goods.getWeight());
                shoppingCartVo.setState(goods.getGoodsStatus());
            }

            shoppingCartVo.setCartID(cart.getCartID());
            shoppingCartVo.setGoodsId(cart.getGoodsId());
            shoppingCartVo.setUserId(cart.getUserId());
            shoppingCartVo.setQuantity(cart.getQuantity());
            shoppingCartVo.setCreateTime(cart.getCreateTime());
            shoppingCartVo.setPrice(cart.getPrice());
            shoppingCartVo.setGoodsName(goods.getGoodsName());
            shoppingCartVo.setMainImage(goods.getMainImage());

          Integer quantity=  cart.getQuantity();
          if(quantity<10){
              shoppingCartVo.setQuantityState("库存紧张");
          }
          cartVoList.add(shoppingCartVo);
        }
        return cartVoList;
    }


    /**
     * 根据用户和商品id，修改购物车中的数量
     * @param cartID
     * @param quantity
     * @return
     */
    @RequestMapping("/updateCartGoodsNum")
    public String updateCartGoodsNum(@RequestParam("cartID")Integer cartID,
                                  @RequestParam("quantity")Integer quantity){

       int num= shoppingcartService.updateCatNum(cartID,quantity);

        String state=null;
        if(num==1){
            state="更改购物车某商品的数量成功";
            System.out.println("更改购物车某商品的数量成功");
        }else {
            state="更改购物车某商品的数量失败";
            System.out.println("更改购物车某商品的数量失败");
        }
        return state;
    }

    /**
     * 点击删除，根据用户id和商品id，删除购物车中的商品
     * @param cartID
     * @return
     */
    @RequestMapping("/deleteCatGoods")
    public int deleteCatGoods(@RequestParam("cartID")Integer cartID){
        int num=shoppingcartService.deleteCatGoods(cartID);
        if(num==1){
            System.out.println("删除购物车某商品成功");
        }else {
            System.out.println("删除购物车某商品失败");
        }
        return num;
    }

    /**
     * 点击结算的时候进行删除购物车里的商品
     *
     * @param cartID
     * @return
     */
    @RequestMapping("/deleteOrderCartGoods")
    public String deleteOrderCartGoods(@RequestParam("cartID") Integer[] cartID) {
        Shoppingcart shoppingcart = new Shoppingcart();
        String state = null;
        //cartID前端通过传入id，所有已经选中的购物车商品的id，进行以逗号分割，进行循环删除。
        for (int i = 0; i < cartID.length; i++) {
            shoppingcart.setCartID(cartID[i]);
            QueryWrapper queryWrapper = new QueryWrapper(shoppingcart);
            int num = shoppingcartMapper.delete(queryWrapper);
            if (num == 1) {
                state = "订单提交，删除Id为："+cartID[i]+"的购物车，删除成功";
            } else {
                state = "订单提交，删除Id为："+cartID[i]+"的购物车，删除失败";
            }
        }
        return state;
    }

    @RequestMapping("/getOneShppingCart")
    public Shoppingcart getOneShppingCart(String loginToken, Integer cartId) {
        User user = userMapper.getCurrentUser(loginToken);
        if (user == null) {
            return null;
        }
        Shoppingcart shoppingcart = new Shoppingcart();
        shoppingcart.setUserId(user.getUserId())
                .setCartID(cartId);
        Shoppingcart shoppingcarts = shoppingcartMapper.selectOne(new QueryWrapper<>(shoppingcart));
        return shoppingcarts;
    }

}



//    //判断该商品是否是打折或秒杀活动的商品。   是的话就原价*打折的价格然后进行存储价格。   不是的话就按原价进行处理
//    int miaoSha=shoppingcartService.sGoodsMiaoSha(goodsId);
////秒杀值等于2，就说明不是秒杀商品
//              if(miaoSha==2){
//
//                      }

//https://www.cnblogs.com/wang-meng/p/5854773.html   https://blog.csdn.net/qq_39537939/article/details/80560782